{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# B 09-1 $ 2 \\times 2 $ 四格表 $\\chi^2$ 检验\n",
    "\n",
    "## 案例\n",
    "\n",
    "研究药物治疗原发性高血压的疗效。随机分为两组，实验组药物治疗，对照组安慰剂。\n",
    "\n",
    "## 分析\n",
    "\n",
    "影响变量：药物治疗 / 安慰剂 ———— 二项分类变量  \n",
    "结果变量：有效 / 无效 ———— 二项分类变量\n",
    "\n",
    "采用 $ 2 \\times 2 $ 四格表 $\\chi^2$ 检验推断两个整体的有效率是否相同.\n",
    "\n",
    "## 假设\n",
    "\n",
    "$ H_0 : p_1 = p_2 $  \n",
    "$ H_1 : p_1 \\neq p_2 $\n",
    "\n",
    "## 计算\n",
    "\n",
    "数据如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div><style>\n",
       ".dataframe > thead > tr,\n",
       ".dataframe > tbody > tr {\n",
       "  text-align: right;\n",
       "  white-space: pre-wrap;\n",
       "}\n",
       "</style>\n",
       "<small>shape: (2, 3)</small><table border=\"1\" class=\"dataframe\"><thead><tr><th>group</th><th>effective_number</th><th>uneffective_number</th></tr><tr><td>str</td><td>i64</td><td>i64</td></tr></thead><tbody><tr><td>&quot;control&quot;</td><td>20</td><td>24</td></tr><tr><td>&quot;experimental&quot;</td><td>21</td><td>5</td></tr></tbody></table></div>"
      ],
      "text/plain": [
       "shape: (2, 3)\n",
       "┌──────────────┬──────────────────┬────────────────────┐\n",
       "│ group        ┆ effective_number ┆ uneffective_number │\n",
       "│ ---          ┆ ---              ┆ ---                │\n",
       "│ str          ┆ i64              ┆ i64                │\n",
       "╞══════════════╪══════════════════╪════════════════════╡\n",
       "│ control      ┆ 20               ┆ 24                 │\n",
       "│ experimental ┆ 21               ┆ 5                  │\n",
       "└──────────────┴──────────────────┴────────────────────┘"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import polars as pl\n",
    "\n",
    "df = pl.read_csv(\"B_09_1-data.csv\")\n",
    "\n",
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "$2 \\times 2\\ \\chi^2$ test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "chi-squared value: 7.007173860622139\n",
      "degrees of freedom: 1\n",
      "p-value: 0.008118373404489128\n"
     ]
    }
   ],
   "source": [
    "from scipy.stats import chi2_contingency\n",
    "\n",
    "result = chi2_contingency(df.select(\"effective_number\", \"uneffective_number\"), correction=True)\n",
    "\n",
    "print(f'chi-squared value: {result.statistic}')\n",
    "print(f'degrees of freedom: {result.dof}')\n",
    "print(f'p-value: {result.pvalue}')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 注：由于自由度为 1，采用 Yates' Correction for continuity, 结果与课本未校正的结果有出入。  \n",
    "\n",
    "P < 0.05，拒绝原假设，认为该药物对高血压的治疗有显著影响。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
